import { config } from "@/config"
import { storage }  from "@/utils/storage"

/**
 * 动态设置浏览器标题
 * @param title 
 */
export const setDocumentTitle = (title?: string) =>{
  document.title = title || config.title
}

/**
 * 按钮权限
 * @param el [DOM]
 * @param id [菜单id]
 * @param type [权限类型] 1:查看,2:添加,3:修改,4:删除, 5:修改密码,6:编辑
 */
export const getPermission = (el:any, id:string, type:string) =>{
  const menuInfos = storage.get('menuInfos') || []
  //const data = flatData(menuInfos,'childrens')
  const data = [{id:'appManager',auth:['1','3','6']},{id:'userManager',auth:['1','2','4']}]
  let permission = data.filter(el => el.id === id).some(d => d.auth.includes(type))
  return permission
}

export const flatData = (arr, type = 'children') => {
  var array:any = []
  function getData(arr, type){
    arr.forEach(res =>{
      var resType = JSON.parse(JSON.stringify(res)) //先克隆一份数据，作为第一层级的填充
      delete resType[type]
      array.push(resType)
      if(Array.isArray(res[type]) && res[type].length > 0){ //若当前child时数组且长度>0，才可进入flag()
        getData(res[type],type)
      } 
    })
    return array
  }
  const data = getData(arr,'childrens')
  const result = data.map(el =>{
    const auth = el.menuAuthInfos || el.authInfos || []
    const id = el.id || el.menuid
    return {
      id,
      name:el.name,
      auth:auth.map(el => el.roleType)
    }
  })
  return result
}


/**
 * 用来获取url中的所有参数 location.search 获取url中'?'符合的字符串
 * @param url 
 * @returns 
 */
export const getQueryParams = (url = document.location.toString()) =>{
  //若url中国含有特殊字符则需要进行解码
  url = decodeURI(url)
  const arr = url.split("?")
  const obj = {}
  if(arr.length > 1){
    const index = arr[1].indexOf("#")
    arr[1] = index === -1 ? arr[1] : arr[1].slice(0,index)
    //将参数分成数组
    const keyValue  = arr[1].split("&")
    for(let i= 0; i < keyValue .length; i++){
      const item:string[] = keyValue [i].split('=')
      obj[item[0]] = decodeURIComponent(item[1])
    }
  }
  return obj
}